package com.dream.keigezhushou.Activity.activity;

import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.dream.keigezhushou.Activity.wigdt.LyricView;
import com.dream.keigezhushou.R;

import java.io.FileDescriptor;
import java.io.IOException;

public class SongLyricActivity extends AppCompatActivity {

    private LyricView mLyricView;
    private MediaPlayer mMediaPlayer;
    private ImageView mButton;
    private SeekBar mSeekBar;
    private int INTERVAL=30;//歌词每行的间隔
    private FileDescriptor mFileDescriptor;
    private String mMp3Path;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_song_lyric);
        //  mp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LyricSync/1.mp3";
/*
//
//        boolean sdCardExist = Environment.getExternalStorageState().equals(
//                android.os.Environment.MEDIA_MOUNTED);
//        if (sdCardExist) {
//            // 获取sd卡存储路径根目录
//            File pathFile = Environment.getExternalStorageDirectory();
//
//            // 按照SD卡指定的路径创建文件夹
//            File absolutPathFile = new File(pathFile.toString() + "/yy.mp3");
//            if (!absolutPathFile.exists()) {
//                absolutPathFile.mkdirs();
//
//            }
//// 在指定的文件夹中创建文件
//            String strPathFileName = pathFile.toString() ;
//
//            File nameFile = new File(strPathFileName);
//            if (!nameFile.exists()) {
//                try {
//                    nameFile.createNewFile();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    Log.i("Show", e.toString());
//                }
//            }
//
//
//            String strTxtData = "";
//            try {
//                FileInputStream fileInputStream = new FileInputStream(absolutPathFile);
//                int length = fileInputStream.available();
//                byte[] buffer = new byte[length];
//                fileInputStream.read(buffer);
//                strTxtData = new String(buffer);
//                fileInputStream.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//
//
//            File writefile = new File(absolutPathFile.toString());
//            FileOutputStream fileOutputStream = null;
//            try {
//                fileOutputStream = new FileOutputStream(writefile);
//                byte[] buffer = strTxtData.getBytes();
//                try {
//                    fileOutputStream.write(buffer);
//                    fileOutputStream.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
*/

            mMp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yy.mp3";
        System.out.println(  mMp3Path);


//        try {
//     /*       mFileDescriptor = getAssets().openFd("yy.mp3").getFileDescriptor();
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
////        AssetManager am = getAssets();
////        try {
////            AssetFileDescriptor afd = am.openFd("yy.mp3");
////            mMediaPlayer = new MediaPlayer();
////            mMediaPlayer.setDataSource(afd.getFileDescriptor(),
////                    afd.getStartOffset(), afd.getLength());
////            mMediaPlayer.prepare();
////            mMediaPlayer.start();
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
//
////        try{
////            FileDescriptor fileDescriptor = getAssets().openFd("yy.mp3").getFileDescriptor();
////
////        }
////        catch(IOException e){
////            e.printStackTrace();
////        }
//
////        AssetManager am = getAssets();
////        try{
////            AssetFileDescriptor fileDescriptor = am.openFd("yy.mp3");
////            mMediaPlayer = new MediaPlayer();
////            mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
////                    fileDescriptor.getStartOffset(),
////                    fileDescriptor.getLength());
////            mMediaPlayer.prepare(); //准备
////        }
////        catch(IOException e){
////            e.printStackTrace();
////        }*/


            mLyricView = (LyricView) findViewById(R.id.mylrc);
            mMediaPlayer = new MediaPlayer();
            // this.requestWindowFeature(Window.FEATURE_NO_TITLE);

            ResetMusic(mMp3Path);
            SerchLrc();
            mLyricView.SetTextSize();

            mButton = (ImageView) findViewById(R.id.iv_words_play);


            mSeekBar = (SeekBar) findViewById(R.id.timeline);
            mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress,
                                              boolean fromUser) {
                    // TODO Auto-generated method stub
                    if (fromUser) {
                        mMediaPlayer.seekTo(progress);
                        mLyricView.setOffsetY(220 - mLyricView.SelectIndex(progress)
                                * (mLyricView.getSIZEWORD() + INTERVAL - 1));

                    }
                }
            });

            mButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    if (mMediaPlayer.isPlaying()) {

                        mMediaPlayer.pause();
                    } else {

                        mMediaPlayer.start();
                        mLyricView.setOffsetY(220 - mLyricView.SelectIndex(mMediaPlayer.getCurrentPosition())
                                * (mLyricView.getSIZEWORD() + INTERVAL - 1));

                    }
                }
            });

            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    ResetMusic(mMp3Path);
                    mLyricView.SetTextSize();
                    mLyricView.setOffsetY(200);
                    mMediaPlayer.start();
                }
            });
            mSeekBar.setMax(mMediaPlayer.getDuration());
            new Thread(new runable()).start();
        }


    public void SerchLrc() {
        String lrc =   mMp3Path;
        lrc = lrc.substring(0, lrc.length() - 4).trim() + ".lrc".trim();
        LyricView.read(lrc);
        mLyricView.SetTextSize();
        mLyricView.setOffsetY(350);
    }

    public void ResetMusic(String path) {

        mMediaPlayer.reset();
        try {

            mMediaPlayer.setDataSource(  mMp3Path);
            mMediaPlayer.prepare();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    class runable implements Runnable {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {

                try {
                    Thread.sleep(100);
                    if (  mMediaPlayer.isPlaying()) {
                        mLyricView.setOffsetY(  mLyricView.getOffsetY() -   mLyricView.SpeedLrc());
                        mLyricView.SelectIndex( mMediaPlayer.getCurrentPosition());
                        mSeekBar.setProgress( mMediaPlayer.getCurrentPosition());
                        mHandler.post(mUpdateResults);
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    Handler mHandler = new Handler();
    Runnable mUpdateResults = new Runnable() {
        public void run() {
            mLyricView.invalidate(); // 更新视图
        }
    };

}
